package ksj.common.utils.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

/**
 * @author wasif.tanveer
 *
 */
public class GenericServiceConsumer {
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	public static JSONObject consumeServiceGET(String serviceURL, String webServiceHost, int port, String applicationContext) {
		JSONObject object = null;
		String json = "";
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			// specify the host, protocol, and port

			// specify the get request
			HttpGet getRequest = new HttpGet(applicationContext + serviceURL);
			HttpHost target = new HttpHost(webServiceHost, port, "http");
			HttpResponse httpResponse = httpclient.execute(target, getRequest);
			HttpEntity entity = httpResponse.getEntity();
			Header[] headers = httpResponse.getAllHeaders();

			for (int i = 0; i < headers.length; i++) {
			}

			BufferedReader br = new BufferedReader(new InputStreamReader((entity.getContent())));
			// HttpEntity entity = httpResponse.getEntity()
			json = IOUtils.toString(br);
			// String json = br.readLine();
			
			object = new JSONObject(json);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
		return object;
	}

	public static JSONObject consumeServiceGET(String serviceURL, String webServiceHost, String applicationContext,
			List<BasicNameValuePair> namevaluePair) {
		JSONObject object = null;
		String json = "";
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			// specify the host, protocol, and port
			HttpHost target = new HttpHost("localhost", 8833, "http");

			// specify the get request

			HttpGet getRequest = new HttpGet(applicationContext + serviceURL);

			HttpResponse httpResponse = httpclient.execute(target, getRequest);
			HttpEntity entity = httpResponse.getEntity();
			Header[] headers = httpResponse.getAllHeaders();

			for (int i = 0; i < headers.length; i++) {
			}

			// if (entity != null) {
			// System.out.println(EntityUtils.toString(entity));
			// }

			BufferedReader br = new BufferedReader(new InputStreamReader((entity.getContent())));
			// HttpEntity entity = httpResponse.getEntity()
			json = IOUtils.toString(br);
			// String json = br.readLine();
			object = new JSONObject(json);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
		return object;
	}

	public static JSONObject consumeServicePOST(String serviceURL, String webServiceHost, String applicationContext,
			String data) {
		JSONObject object = null;
		String json = "";
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			// specify the host, protocol, and port

			HttpHost target = new HttpHost("localhost", 8833, "http");

			// specify the get request
			HttpPost postRequest = new HttpPost(applicationContext + serviceURL);
			StringEntity e = new StringEntity(data);
			e.setContentType("application/json");
			postRequest.setEntity(e);
			// postRequest.setHeader("Content-Type", "application/json");
			// postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			System.out.println("executing request to " + target);
			HttpResponse httpResponse = httpclient.execute(target, postRequest);
			HttpEntity entity = httpResponse.getEntity();
			System.out.println(httpResponse.getParams());
			System.out.println("----------------------------------------");
			System.out.println(httpResponse.getStatusLine());
			Header[] headers = httpResponse.getAllHeaders();

			for (int i = 0; i < headers.length; i++) {
				System.out.println(headers[i]);
			}
			System.out.println("----------------------------------------");

			// if (entity != null) {
			// System.out.println(EntityUtils.toString(entity));
			// }

			BufferedReader br = new BufferedReader(new InputStreamReader((entity.getContent())));
			// HttpEntity entity = httpResponse.getEntity()
			json = IOUtils.toString(br);
			object = new JSONObject(json);
			Gson gson = new Gson();

			// String output;
			// System.out.println("Output from Server .... \n");
			// while ((output = br.readLine()) != null) {
			// System.out.println(output);
			// }

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
		return object;
	}

	public static JSONObject consumeServicePOST(String serviceURL, String webServiceHost, int port, String applicationContext,
			List<BasicNameValuePair> nameValuePairs) {
		JSONObject object = null;
		String json = "";
		// BasicNameValuePair nvp;
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			// specify the host, protocol, and port
			HttpHost target = new HttpHost(webServiceHost, port, "http");

			// specify the get request
			HttpPost postRequest = new HttpPost(applicationContext + serviceURL);
			postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// postRequest.setHeader(nvp.getName(),nvp.getValue());
			System.out.println("executing request to " + target);
			HttpResponse httpResponse = httpclient.execute(target, postRequest);
			HttpEntity entity = httpResponse.getEntity();
			System.out.println(httpResponse.getParams());
			System.out.println("----------------------------------------");
			System.out.println(httpResponse.getStatusLine());
			Header[] headers = httpResponse.getAllHeaders();

			for (int i = 0; i < headers.length; i++) {
				System.out.println(headers[i]);
			}
			System.out.println("----------------------------------------");

			// if (entity != null) {
			// System.out.println(EntityUtils.toString(entity));
			// }

			BufferedReader br = new BufferedReader(new InputStreamReader((entity.getContent())));
			// HttpEntity entity = httpResponse.getEntity()
			json = IOUtils.toString(br);
			object = new JSONObject(json);

			// String output;
			// System.out.println("Output from Server .... \n");
			// while ((output = br.readLine()) != null) {
			// System.out.println(output);
			// }

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
		return object;
	}

	public static HttpResponse consumeServicePOST(String serviceURL, String webServiceHost, String applicationContext,
			URIBuilder builderWithParams, String protocol, HttpClient httpclient) {
		// BasicNameValuePair nvp;
		HttpResponse httpResponse = null;
		try {
			// specify the host, protocol, and port

			builderWithParams.setScheme(protocol);
			builderWithParams.setHost(webServiceHost).setPath(applicationContext + serviceURL);

			URI uri = builderWithParams.build();
			// HttpHost target = new HttpHost(webServiceHost, 80, protocol);

			// specify the get request
			// HttpPost postRequest = new HttpPost(applicationContext +
			// serviceURL);
			// postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpPost postRequest = new HttpPost(uri);

			// postRequest.setHeader(nvp.getName(),nvp.getValue());
			// System.out.println("executing request to " + target);
			// HttpResponse httpResponse = httpclient.execute(target,
			// postRequest);
			httpResponse = httpclient.execute(postRequest);
			// HttpEntity entity = httpResponse.getEntity();
			// System.out.println(httpResponse.getParams());
			// System.out.println("----------------------------------------");
			// System.out.println(httpResponse.getStatusLine());
			// Header[] headers = httpResponse.getAllHeaders();
			//
			// for (int i = 0; i < headers.length; i++) {
			// System.out.println(headers[i]);
			// }
			// System.out.println("----------------------------------------");
			//
			// responseStr = new
			// String(EntityUtils.toString(httpResponse.getEntity()).getBytes("ISO_8859_1"),
			// "GBK");
			// System.out.println(responseStr);
			// if (entity != null) {
			// System.out.println(EntityUtils.toString(entity));
			// }

			// BufferedReader br = new BufferedReader(new
			// InputStreamReader((entity.getContent())));
			// // HttpEntity entity = httpResponse.getEntity()
			// json = IOUtils.toString(br);
			// object = new JSONObject(json);

			// String output;
			// System.out.println("Output from Server .... \n");
			// while ((output = br.readLine()) != null) {
			// System.out.println(output);
			// }

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			// httpclient.getConnectionManager().shutdown();
		}
		return httpResponse;
	}

	public static String consumeServicePOST(String serviceURL, String webServiceHost, String applicationContext,
			URIBuilder builderWithParams, HttpClient httpclient) {
		String responseStr = "";
		// BasicNameValuePair nvp;
		// HttpClient httpclient = new DefaultHttpClient();
		// httpclient = wrapClient(httpclient);
		try {
			// specify the host, protocol, and port

			builderWithParams.setScheme("https");
			builderWithParams.setHost(webServiceHost).setPath(serviceURL);

			URI uri = builderWithParams.build();
			HttpHost target = new HttpHost(webServiceHost, 80, "https");

			// specify the get request
			// HttpPost postRequest = new HttpPost(applicationContext +
			// serviceURL);
			// postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpPost postRequest = new HttpPost(uri);

			// postRequest.setHeader(nvp.getName(),nvp.getValue());
			System.out.println("executing request to " + target);
			// HttpResponse httpResponse = httpclient.execute(target,
			// postRequest);
			HttpResponse httpResponse = httpclient.execute(postRequest);
			HttpEntity entity = httpResponse.getEntity();
			System.out.println(httpResponse.getParams());
			System.out.println("----------------------------------------");
			System.out.println(httpResponse.getStatusLine());
			Header[] headers = httpResponse.getAllHeaders();

			for (int i = 0; i < headers.length; i++) {
				System.out.println(headers[i]);
			}
			System.out.println("----------------------------------------");

			responseStr = new String(EntityUtils.toString(httpResponse.getEntity()).getBytes("ISO_8859_1"), "GBK");
			System.out.println(responseStr);
			// if (entity != null) {
			// System.out.println(EntityUtils.toString(entity));
			// }

			// BufferedReader br = new BufferedReader(new
			// InputStreamReader((entity.getContent())));
			// // HttpEntity entity = httpResponse.getEntity()
			// json = IOUtils.toString(br);
			// object = new JSONObject(json);

			// String output;
			// System.out.println("Output from Server .... \n");
			// while ((output = br.readLine()) != null) {
			// System.out.println(output);
			// }

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			// httpclient.getConnectionManager().shutdown();
		}
		return responseStr;
	}

	public static HttpClient wrapClient(HttpClient base) {
		try {
			SSLContext ctx = SSLContext.getInstance("TLSv1.2");
			X509TrustManager tm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			// base.getConnectionManager().getSchemeRegistry().register(new
			// Scheme("https", 443, ssf));
			// ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			ClientConnectionManager ccm = base.getConnectionManager();
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", 443, ssf));
			return new DefaultHttpClient(ccm, base.getParams());
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	/*
	 * public static JSONObject consumeServicePOST(String serviceURL, String
	 * applicationContext, BasicNameValuePair nameValuePair) { JSONObject object
	 * = null; DefaultHttpClient httpclient = new DefaultHttpClient(); try { //
	 * specify the host, protocol, and port HttpHost target = new
	 * HttpHost(WebUtils.WEBSERVICE_HOST_URL,
	 * Integer.parseInt(PropertiesUtils.getProperty(WebUtils.HOST_PORT)),
	 * PropertiesUtils.getProperty(WebUtils.HOST_PROTOCOL_HTTP));
	 * 
	 * // specify the get request HttpPost postRequest = new
	 * HttpPost(applicationContext + serviceURL); //postRequest.setEntity(new
	 * UrlEncodedFormEntity(nameValuePair));
	 * postRequest.setHeader(nameValuePair.getName(),nameValuePair.getValue());
	 * System.out.println("executing request to " + target); HttpResponse
	 * httpResponse = httpclient.execute(target, postRequest); HttpEntity entity
	 * = httpResponse.getEntity(); System.out.println(httpResponse.getParams());
	 * System.out.println("----------------------------------------");
	 * System.out.println(httpResponse.getStatusLine()); Header[] headers =
	 * httpResponse.getAllHeaders();
	 * 
	 * for (int i = 0; i < headers.length; i++) {
	 * System.out.println(headers[i]); }
	 * System.out.println("----------------------------------------");
	 * BufferedReader br = new BufferedReader(new InputStreamReader(
	 * (entity.getContent()))); // HttpEntity entity = httpResponse.getEntity()
	 * String json = IOUtils.toString(br); object = new JSONObject(json); Gson
	 * gson = new Gson(); } catch (Exception e) { e.printStackTrace(); } finally
	 * { // When HttpClient instance is no longer needed, // shut down the
	 * connection manager to ensure // immediate deallocation of all system
	 * resources httpclient.getConnectionManager().shutdown(); } return object;
	 * }
	 */

	public static JSONObject consumeServiceDELETE(String serviceURL, String webServiceHost, String applicationContext) {
		JSONObject object = null;
		String json = "";
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			// specify the host, protocol, and port
			HttpHost target = new HttpHost("localhost", 8833, "http");

			// specify the get request
			HttpDelete deleteRequest = new HttpDelete(applicationContext + serviceURL);

			HttpResponse httpResponse = httpclient.execute(target, deleteRequest);
			HttpEntity entity = httpResponse.getEntity();
			Header[] headers = httpResponse.getAllHeaders();

			for (int i = 0; i < headers.length; i++) {
			}

			// if (entity != null) {
			// System.out.println(EntityUtils.toString(entity));
			// }

			BufferedReader br = new BufferedReader(new InputStreamReader((entity.getContent())));
			// HttpEntity entity = httpResponse.getEntity()
			json = IOUtils.toString(br);
			object = new JSONObject(json);

			// String output;
			// System.out.println("Output from Server .... \n");
			// while ((output = br.readLine()) != null) {
			// System.out.println(output);
			// }

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
		return object;
	}

	public static JSONObject consumeServicePUT(String serviceURL, String webServiceHost, String applicationContext) {
		JSONObject object = null;
		String json = "";
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			// specify the host, protocol, and port
			HttpHost target = new HttpHost("localhost", 8833, "http");

			// specify the get request
			HttpPut putRequest = new HttpPut(applicationContext + serviceURL);
			HttpResponse httpResponse = httpclient.execute(target, putRequest);
			HttpEntity entity = httpResponse.getEntity();
			Header[] headers = httpResponse.getAllHeaders();

			for (int i = 0; i < headers.length; i++) {
			}

			// if (entity != null) {
			// System.out.println(EntityUtils.toString(entity));
			// }

			BufferedReader br = new BufferedReader(new InputStreamReader((entity.getContent())));
			// HttpEntity entity = httpResponse.getEntity()
			json = IOUtils.toString(br);
			object = new JSONObject(json);

			// String output;
			// System.out.println("Output from Server .... \n");
			// while ((output = br.readLine()) != null) {
			// System.out.println(output);
			// }

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
		return object;
	}
}
